import _ from 'lodash';
import path from 'path';
import fs from 'fs-extra';
import validator from 'validator';
import Promise from 'promise';
import config from '../config';
import * as cache from '../common/cache';
import xmlbuilder from 'xmlbuilder';
import { apiPrefix } from '../../config';
import * as ResultMsg from '../constrants/ResultMsg';
import { errorRender, successRender } from '../common/response';
import { checkId, checkName, checkDoc } from '../common/check';
import suggestGoodTopics from '../components/suggestTopicsPanel';
import createPanel from '../components/createPanel';
import { UserProxy, TopicProxy, TopicCollectProxy, ZoneProxy, ProfileProxy, StaticProxy } from '../proxy';

export {
  indexPage,
  zonePage,
  cmsPage,
  cmsAppPage,
  cmsMenuPage,
  cmsUserPage,
  cmsAudioPage,
  cmsStaticPage,
  cmsProfilePage,
  cmsScript,
  signupPage,
  signinPage,
  searchPasswordFromMailPage,
  inputSearchPasswordPage,
  resetPasswordPage,
  myMessagesPage,
  allMessagePage,
  showTopicPage,
  createTopicPage,
  editTopicPage,
  userPage,
  userTopicsPage,
  userCollectTopicsPage,
  userRepliesPage,
  settingPage,
  staticPage,
  createStaticPage,
  editStaticPage,
  repoPage,
  repoConfigPage
};

async function indexPage(req, res, next) {
  const that = this;
  const appId = res.locals.appId;
  const blocks = [];
  const zones = res.locals.zones || [];

  try {
    if (zones.length < 1) return errorRender(req, res, { err: '还没有创建板块' });

    const profile = await ProfileProxy.findOne(appId);
    const html = await suggestGoodTopics(appId, zones[0]);
    const data = {
      selectedKey: 'home',
      blocks: zones,
      suggestHtml: html,
      profile,
    };

    successRender(req, res, data, 'index.html');
  } catch (err) {
    next(err);
  }
}

async function zonePage(req, res) {
  const appId = res.locals.appId;
  const zoneKey = req.params.key;
  const zoneTemplate = req.params.template;

  try {
    const zone = await ZoneProxy.findOneById(appId, req.query.zoneId);
    const html = await createPanel(appId, zone);

    const data = {
      appId: appId,
      selectedKey: zoneKey,
      zoneKey: zoneKey,
      zoneTemplate: zoneTemplate,
      zoneId: req.query.zoneId,
      type: req.query.type,
      createPanel: html,
    };

    let page = 'template/' + zoneTemplate + '/index';
    successRender(req, res, data, page);
  } catch (err) {
    next(err);
  }
}

function cmsPage(req, res) {
  res.render('cms/index', { pageTitle: '全部', navTab: 'topic'});
}

function cmsAppPage(req, res) {
  res.render('cms/appInfo', { pageTitle: '全部'});
}

function cmsMenuPage(req, res, next) {
  res.render('menu/index', { navTab: 'menu' });
}

function cmsUserPage(req, res, next) {
  res.render('cms/user');
}

function cmsAudioPage(req, res, next) {
  res.render('audio/index');
}

function cmsStaticPage(req, res, next) {
  res.render('static/index');
}

function cmsProfilePage(req, res, next) {
  res.render('cms/profile');
}

function cmsScript(req, res) {
  res.render('cms/script');
}

function signupPage(req, res) {
  res.render('sign/signup');
}

function signinPage(req, res) {
  req.session._loginReferer = req.headers.referer;
  res.render('sign/signin');
}

function searchPasswordFromMailPage(req, res) {
  res.render('sign/searchPasswordFromMail');
}

async function inputSearchPasswordPage(req, res) {
  const appId = res.locals.appId;
  const key = validator.trim(req.query.key || '');
  const loginname = validator.trim(req.query.loginname || '');

  try {
    let user = await UserProxy.findOne(appId, {loginname, retrieveKey: key});
    await checkDoc(user);
    res.render('sign/inputSearchPassword', { key, loginname });
  } catch (err) {
    next(err);
  }
}

function resetPasswordPage(req, res, next) {
  const userId = req.session.user._id;
  res.render('sign/resetPassword', { userId });
}

function myMessagesPage(req, res, next) {
  const userId = validator.trim(req.session.user._id || '');
  const type = req.params.type || 'read';
  res.render('message/index', { userId, type });
}

function allMessagePage(req, res, next) {
  const type = req.query.type || 'read';
  const userId = validator.trim(req.session.user._id || '');
  res.render('message/all', { userId, type });
}

async function showTopicPage(req, res, next) {
  const appId = res.locals.appId;
  const topicId = req.params.id;
  const zoneKey = req.params.key;
  const zoneTemplate = req.params.template;
  const userId = req.session.user && req.session.user._id ? req.session.user._id : '';

  try {
    await checkId(topicId);
    const topic = await TopicProxy.findFullOneById(appId, topicId);

    if (userId) {
      const collect = await TopicCollectProxy.findOne(appId, userId, topicId);

      if (collect) {
        topic.isCollect = true;
      } else {
        topic.isCollect = false;
      }
    }

    let page = 'template/' + zoneTemplate + '/show';
    successRender(req, res, { topic }, page);
  } catch (err) {
    next(err);
  }
}

function createTopicPage(req, res, next) {
  const zoneKey = req.params.key;
  const zoneTemplate = req.params.template;

  let page = 'template/' + zoneTemplate + '/create';
  res.render(page);
}

function editTopicPage(req, res, next) {
  const zoneKey = req.params.key;
  const zoneTemplate = req.params.template;
  const topicId = req.params.id;

  let page = 'template/' + zoneTemplate + '/edit';
  res.render(page, { topicId });
}

function userPage(req, res, next) {
  res.render('user/index');
}

async function userTopicsPage(req, res, next) {
  const appId = res.locals.appId;
  const userName = req.params.name;

  try {
    await checkName(userName)
    let user = await UserProxy.findOneByName(appId, userName);
    await checkDoc(user);
    successRender(req, res, { userId: user._id, userName: user.loginname }, 'user/topics');
  } catch (err) {
    next(err)
  }
}

async function userCollectTopicsPage(req, res, next) {
  const appId = res.locals.appId;
  const userName = req.params.name;

  try {
    await checkName(userName)
    let user = await UserProxy.findOneByName(appId, userName);
    await checkDoc(user);
    successRender(req, res, { userId: user._id, userName: user.loginname }, 'user/collect_topics');
  } catch (err) {
    next(err)
  }
}

function userRepliesPage(req, res, next) {
  const userName = req.params.name;
  res.render('user/replies', { userName });
}

function settingPage(req, res, next) {
  const userId = req.session.user._id;
  res.render('user/setting', { userId, userId });
}

// static page

async function staticPage(req, res, next) {
  const appId = res.locals.appId;
  const name = req.params.name;

  try {
    let doc = await StaticProxy.findOneByName(appId, name);
    if (!doc) {
      return errorRender(req, res, {err: '没有对应的静态文件'});
    }

    successRender(req, res, {doc: doc}, 'static/show.html');
  } catch(err) {
    next(err);
  }
}

function createStaticPage(req, res, next) {
  res.render('static/create', {pageTitle: '创建静态页面'});
}

async function editStaticPage(req, res, next) {
  const appId = res.locals.appId;
  const name = req.params.name;

  try {
    let doc = await StaticProxy.findOneByName(appId, name);
    if(!doc) {
      return errorRender(req, res, {msg: 'not found.'});
    }

    successRender(req, res, {staticId: doc._id}, 'static/edit');
  } catch(err) {
    next(err);
  }
}

function repoPage(req, res, next) {
  res.render('wiki/index');
}

function repoConfigPage(req, res, next) {
  res.render('wiki/config');
}
